package cn.wolfcode.crm.realms;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    // 注入 Service
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    // 复写 getName
    @Override
    public String getName() {
        return "MyRealm";
    }

    /**
     * 权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("-------------------88888888888888888888888888----------------------");
        Employee emp = (Employee) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 判断是否是 管理员
        if (emp.isAdmin()) {
            info.addRole("ADMIN");
            info.addStringPermission("*:*");
            System.out.println("-------------------另外で一条，华丽の分割线----------------------");
        } else {
            Long empId = emp.getId();
            // 获取 角色信息
            info.addRoles(roleService.getSnByEmployeeId(empId));
            // 获取 权限信息
            info.addStringPermissions(permissionService.selectByEmployeeId(empId));
        }
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取 用户名
        String username = (String) token.getPrincipal();
        // 获取 用户
        Employee emp = employeeService.getByUsername(username);

        if (emp != null) {
            return new SimpleAuthenticationInfo(emp, emp.getPassword(), ByteSource.Util.bytes("Fizz_kai"),getName());
        }
        return null;
    }
}
